<?php

namespace app\common\model;

use app\common\exception\VersionException;
use think\facade\Cache;

class Admin extends BaseModel
{

    public function updateByVersion($updateData)
    {
        if (!is_array($updateData) && method_exists($updateData, "toArray")) {
            $updateData = $updateData->toArray();
        }
        $findData = $this->findById($updateData["id"]);
        $version = $updateData["version"];
        $updateData["version"] = ($findData["version"] + 1);
        $count = $this->where("id", $updateData["id"])->where("version", $version)->update($updateData);
        if ($count !== 1) throw new VersionException("修改失败");
        Cache::rm($this->name . ":" . $updateData["id"]);
    }


    /**
     * 重置用户密码
     * @param $userId
     * @param $newPassword
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resetPassword($userId, $newPassword)
    {
        $password = $this->encryptPassword($newPassword);
        $ret = $this->where(['id' => $userId])->update(['password' => $password]);
        return $ret;
    }

    // 密码加密
    protected function encryptPassword($password, $salt = '', $encrypt = 'md5')
    {
        return $encrypt($password . $salt);
    }

    public function getDictionary()
    {
        return [
            "status" => $this->getStatusList(),
            "is_delete" => $this->getDeleteList()
        ];
    }

}
